// ----------------------------------------------------------------------------//
// ProgressAsyncTask.java
// Created by user On 2012-11-22
package com.demo.framework.ui;

import com.demo.framework.widget.TaskProgressDialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

/**
 * 
 * @ClassName: ProgressAsyncTask
 * @Description: TODO(扩展AsyncTask，提供ProgressDialog和AlertDialog)
 * @author 谢云腾
 * @date 2013-3-25 下午03:21:41
 * @version 1.0
 */
public abstract class ProgressAsyncTask extends AsyncTask<Void, Integer, Integer> implements
        DialogInterface.OnClickListener {

    //正在执行
    static public final int RESULT_RUNNING = -1;
    
    //init
    static public final int RESULT_INIT = 0;
    
    // 正确结果
    static public final int RESULT_OK = 1;

    //错误结构
    static public final int RESULT_ERROR = 2;

    // 定义progress bar显示的类型
    public static final int PROGRESS_BAR_TYPE_NONE = 0;

    public static final int PROGRESS_BAR_TYPE_PROGRESS_DIALOG = 1;

    public static final int PROGRESS_BAR_USER_DEFINED = 2;

    // progress Dialog   自定义progress 类型
    protected TaskProgressDialog progressDialog;

    // progress 类型
    private int progress_bar_type = PROGRESS_BAR_TYPE_NONE;

    protected Activity activity;

    protected long startTime, stopTime;

    int result = RESULT_INIT;

    /**
     * @param activity
     *            当前Activity
     */
    public ProgressAsyncTask(Activity activity) {
        this(activity, "", "", -1);
    }

    /**
     * 如果layoutId 为-1则使用progress dialog 否则使用自定义的加载框
     * 
     * @param activity
     * @param layoutId
     */
    public ProgressAsyncTask(Activity activity, int layoutId) {
        this(activity, "", "", layoutId);
    }

    /**
     * 当前Activity
     * 
     * @param activity
     *            当前Activity
     * @param title
     *            ProgressDialog Title
     * @param message
     *            ProgressDialog Message
     */
    public ProgressAsyncTask(Activity activity, String title, String message, int layoutId) {
        assert activity != null;
        this.activity = activity;
        if (layoutId != -1) {// 显示用户自定义的progress bar
            progressDialog = TaskProgressDialog.show(activity, message);
        }
        else if (title != null) {// 显示progress dialog

            // progressDialog = TaskProgressDialog.show(activity,title,message);
            this.progress_bar_type = PROGRESS_BAR_TYPE_PROGRESS_DIALOG;
        }
        else {// 不显示任何的提示框
            this.progress_bar_type = PROGRESS_BAR_TYPE_NONE;
        }

    }

    /**
    * @Title: setProgressDlgMessage 
    * @Description: TODO(设置 progress 消息) 
    * @param @param msg  内容
    * @return void    返回类型 
    * @throws
     */
    public void setProgressDlgMessage(final String msg) {
        assert activity != null;
        assert progressDialog != null;
        if (this.activity instanceof BaseActivity) {
            BaseActivity ba = (BaseActivity) activity;
            ba.post(new Runnable() {

                @Override
                public void run() {
                    ProgressAsyncTask.this.progressDialog.setMessage(msg);
                }

            });
        }
    }

    /**
     * 
    * @Title: setProgressDlgMessage 
    * @Description: TODO(设置 progress 消息，以及消失显示时间) 
    * @param @param msg   消息内容
    * @param @param waittingTime 显示时间
    * @return void    返回类型 
    * @throws
     */
    public void setProgressDlgMessage(final String msg, final int waittingTime) {
        assert activity != null;
        assert progressDialog != null;

        if (this.activity instanceof BaseActivity) {
            BaseActivity ba = (BaseActivity) activity;
            ba.post(new Runnable() {

                @Override
                public void run() {
                    ProgressAsyncTask.this.progressDialog.setMessage(msg);
                }

            }, waittingTime);
        }
    }

    // ------------------------------------------------------------------------------

    /**
     * 任务操作
     * 
     * @return
     */
    abstract protected int doTask();

    /**
     * ProgressDialog 和 AlertDialog按钮时间
     * 
     * @param dialog
     *            dialog
     * @param button
     *            按钮
     * @param result
     *            task result
     */
    protected void onButtonClicked(DialogInterface dialog, int button, int result) {
    }

    /**
     * 显示ProgressDialog
     */
    protected void showProgress() {
        progressDialog.show();
    }

    /**
     * 关闭ProgressDialog
     */
    protected void dismissProgress() {
        if (/* !activity.isFinishing() && */(progressDialog != null) && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * 显示 Alert Dialog,在本类 onButtonClicked 方法中处理。
     * 
     * @param title
     *            AlertDialog title
     * @param message
     *            AlertDialog Message
     * @param buttonTitle
     *            AlertDialog Positive Button Title
     */
    public void alert(String title, String message, String buttonTitle) {
        new AlertDialog.Builder(activity).setTitle(title).setMessage(message).setPositiveButton(buttonTitle, this)
                .show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        onButtonClicked(dialog, which, result);
    }

    public void execute() {
        super.execute(new Void[] {});

    }

    /**
     * (非 Javadoc)
     * <p>
     * Title: onPostExecute
     * </p>
     * <p>
     * Description: 在doInBackground 执行完成后，onPostExecute 方法将被UI thread调用，
     * 后台的计算结果将通过该方法传递到UI thread
     * </p>
     * 
     * @param result
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if (this.progress_bar_type == PROGRESS_BAR_TYPE_PROGRESS_DIALOG) {
            dismissProgress();
        }
        // else if (this.progress_bar_type == PROGRESS_BAR_USER_DEFINED) {
        // hideCustomizedProgressView();
        // }

    }

    /**
     * (非 Javadoc)
     * <p>
     * Title: onPreExecute
     * </p>
     * <p>
     * Description: 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作，如在界面上显示一个进度条
     * </p>
     * 
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (this.progress_bar_type == PROGRESS_BAR_TYPE_PROGRESS_DIALOG) {
            showProgress();
        }
        // else if (this.progress_bar_type == PROGRESS_BAR_USER_DEFINED) {
        // this.modal = this.getModal();
        // this.rootFrameLayout = this.getRootFrameLayout();
        // displayCustomizedProgressView();
        // }

    }

    /**
     * (非 Javadoc)
     * <p>
     * Title: doInBackground
     * </p>
     * <p>
     * Description: 将在onPreExecute 方法执行后马上执行，该方法运行在后台线程中。
     * 这里将主要负责执行那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。 该方法是抽象方法，子类必须实现
     * </p>
     * 
     * @param params
     * @return
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Integer doInBackground(Void... params) {
        startTime = System.currentTimeMillis();
        result = RESULT_RUNNING;
        try {
            result = doTask();
        }
        catch(Exception e) {
            result = RESULT_ERROR;
        }
        stopTime = System.currentTimeMillis();
        return result;
    }

    /**
     * 获得任务启动时间
     * 
     * @return
     */
    public long getStartTime() {
        return startTime;
    }

    /**
     * 获得任务结束时间
     * 
     * @return
     */
    public long getStopTime() {
        return stopTime;
    }

    /**
     * 获得任务持续时间
     * 
     * @return
     */
    public long getTimeSpan() {
        return stopTime - startTime;
    }

}

// ----------------------------------END---------------------------------------//